﻿using System;
using System.Linq;
using System.Reflection;
using System.Windows;
using RegeditNavigator.SingleInstance;

namespace RegeditNavigator
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            AppSingleton.CheckForAnotherInstance();

            base.OnStartup(e);
            AppDomain.CurrentDomain.AssemblyResolve += CurrentDomainOnAssemblyResolve;
        }

        private Assembly CurrentDomainOnAssemblyResolve(object sender, ResolveEventArgs args)
        {
            var dllName = args.Name.Contains(',')
                              ? args.Name.Substring(0, args.Name.IndexOf(',')) + ".dll"
                              : args.Name;

            dllName = GetType().Namespace + "." + dllName;

            using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(dllName))
            {
                if (stream == null) return null;

                var assemblyBytes = new byte[stream.Length];

                stream.Read(assemblyBytes, 0, assemblyBytes.Length);

                return Assembly.Load(assemblyBytes);
            }
        }
    }
}
